import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../util/Toast.dart';
import '../../base/Constant.dart';
// import 'package:panda/base/SignType.dart';
import '../../entity/goods_fs_entity.dart';
// import 'package:panda/goods/GoodsDetail.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import '../../base/Constant.dart';
import './QGGoodsDetail.dart';

class QiangGouChildPage extends StatefulWidget {
  String time = "";
  QiangGouChildPage({Key key, @required this.time}) : super(key: key);

  @override
  _QiangGouChildPageState createState() => _QiangGouChildPageState();
}

class _QiangGouChildPageState extends State<QiangGouChildPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller = new EasyRefreshController();
  List<GoodsFsDataData> dataList = new List();
  int page = 1;
  @override
  void initState() {
    super.initState();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = createSignType(Api.URL_GOODSFS_LIST);
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODSFS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    if (mounted) if (page == 1) {
      _controller.finishRefresh();
    } else {
      _controller.finishLoad();
    }
    if (userMap['code'] != 1) {
      // Fluttertoast.showToast(msg: userMap['msg']);
      Toast.toast(context, msg: userMap['msg']);
      return;
    }
    GoodsFsEntity homeListEntity = new GoodsFsEntity.fromJson(userMap);
    if (mounted) if (page == 1) {
      dataList.clear();
      dataList.addAll(homeListEntity.data.datas);
      _controller.finishRefresh();
      _controller.resetLoadState();
    } else {
      dataList.addAll(homeListEntity.data.datas);
      _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
    }
    if (dataList.length == 0) {
      Toast.toast(context, msg: "暂无抢购信息");
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        backgroundColor: f0Color,
        body: Stack(
          children: <Widget>[
            ClipPath(
                // 只裁切底部的方法
                clipper: BottonClipper(),
                child: Container(
                  decoration: BoxDecoration(
                    color: Color.fromARGB(255, 255, 140, 16),
                  ),
                  // color: mainColor,
                  height: ScreenUtil.getInstance().setWidth(DP_200) * 2,
                )),
            new EasyRefresh(
              onRefresh: () {
                page = 1;
                loadList();
              },
              onLoad: () {
                page++;
                loadList();
              },
              enableControlFinishLoad: true,
              controller: _controller,
              enableControlFinishRefresh: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return new GestureDetector(
                      child: renderRow(context, index), onTap: () {});
                },
                itemCount: dataList.length,
              ),
            ),
          ],
        ));
  }

  renderRow(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_20),
          0),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.network(
                  Api.BaseUrl +
                      dataList[index].goodsMsg.url.replaceAll('\\', '/'),
                  width: ScreenUtil.getInstance().setHeight(DP_160),
                  fit: BoxFit.fill,
                  height: ScreenUtil.getInstance().setHeight(DP_160)),
            ),
            Container(
              width: ScreenUtil.getInstance().setHeight(DP_15),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(dataList[index].goodsMsg.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87)),
                  Text('每人限购' + dataList[index].limit_num + "件",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(SMALL_FONT_SIZE - 3),
                          color: Colors.black38)),
                  Container(
                    height: ScreenUtil.getInstance().setHeight(DP_15),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(
                        0, 0, ScreenUtil.getInstance().setHeight(DP_100), 0),
                    decoration: BoxDecoration(
                        // color: Color.fromARGB(255, 232, 78, 173),
                        color: hexToColor('#f5e0d7'),
                        border: Border.all(color: mainColor, width: 1),
                        borderRadius: BorderRadius.circular(100)),
                    child: new LinearPercentIndicator(
                      animation: true,
                      animationDuration: 1000,
                      lineHeight: ScreenUtil.getInstance().setHeight(DP_30),
                      percent: int.parse(dataList[index].sales_num) /
                          int.parse(dataList[index].all_num),
                      center: Text(
                          '已抢' +
                              ((int.parse(dataList[index].sales_num) *
                                      100 /
                                      int.parse(dataList[index].all_num)))
                                  .toString() +
                              '%',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NINIEST_FONT_SIZE),
                              color: mainColor)),
                      backgroundColor: white,
                      linearStrokeCap: LinearStrokeCap.roundAll,
                      progressColor: hexToColor('#f5e0d7'),
                    ),
                  ),
                  Container(
                    height: ScreenUtil.getInstance().setHeight(DP_10),
                  ),
                  Container(
                    height: ScreenUtil.getInstance().setHeight(DP_10),
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(MONEY + dataList[index].price,
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(BIG_FONT_SIZE),
                                color: mainColor)),
                      ),
                      new Container(
                        height: ScreenUtil.getInstance().setHeight(DP_50),
                        // decoration: new BoxDecoration(
                        //     color: mainColor,
                        //     borderRadius: BorderRadius.circular(5.0)),
                        child: RaisedButton(
                          child: Text('去抢购',
                              style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE),
                              )),
                          textColor: Colors.white,
                          // elevation: 20,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)),
                          color: mainColor,
                          onPressed: () {
                            Navigator.of(context)
                                .push(MaterialPageRoute(builder: (context) {
                              return QGGoodsDetailPage(
                                goods_id: dataList[index].goods_id,
                                img: dataList[index].goodsMsg.url,
                                type: 1,
                                id: dataList[index].id,
                                limit_num: dataList[index].limit_num,
                                all_num: dataList[index].all_num,
                                start_time: dataList[index].start_time,
                                end_time: dataList[index].end_time,
                                sale_num: dataList[index].sales_num,
                              );
                            }));
                          },
                        ),
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class BottonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.lineTo(0, 0);
    path.lineTo(0, size.height - 50);
    var firstControlPoint = Offset(size.width / 2, size.height);
    var firstEndPont = Offset(size.width, size.height - 50);
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
        firstEndPont.dx, firstEndPont.dy);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
